﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Newtonsoft.Json;
using System.Collections;
using System.Web.Script.Serialization;

namespace dbcaac
{
    public class JsonHelper
    {
        public static string SqlDataReader2JsonForEasyUIDataGrid(int total, System.Data.SqlClient.SqlDataReader reader)
        {
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);

            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                writer.Formatting = Formatting.Indented;
                writer.WriteStartObject();
                writer.WritePropertyName("total");
                writer.WriteValue(total);
                writer.WritePropertyName("rows");
                writer.WriteStartArray();
                while (reader.Read())
                {
                    writer.WriteStartObject();
                    for (int index = 0; index < reader.FieldCount; index++)
                    {
                        writer.WritePropertyName(reader.GetName(index));
                        writer.WriteValue(reader.GetValue(index));
                    }
                    writer.WriteEndObject();
                }
                writer.WriteEnd();
                writer.WriteEndObject();
            }

            return sb.ToString();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <param name="pid"></param>
        /// <param name="reader"></param>
        /// <returns></returns>
        public static string GetGridTreeJSON(   string id,      // id field for treegrid
                                                string pid,     // pid field for treegrid
                                                System.Data.SqlClient.SqlDataReader reader  // data source
                                            )
        {
            // 1、把DataReader转成哈希表
            var list = new List<Hashtable>();
            while (reader.Read())
            {
                var item = new Hashtable();

                for (var i = 0; i < reader.FieldCount; i++)
                {
                    var name = reader.GetName(i);
                    item[name] = reader[i];
                }
                list.Add(item);
            }

            var idx = new Hashtable();        // data indices for calculation
            var tg = new List<Hashtable>();  // data prepared
            // 2、获得索引列表
            foreach (var item in list)
            {
                if (item.ContainsKey(id))
                    idx[item[id].ToString()] = item;
            }
            // 3、建立树形结构
            foreach (var item in list)
            {
                if (!item.ContainsKey(id))
                    continue;

                if (!item.ContainsKey(pid) || (item[pid] == null) || !idx.ContainsKey(item[pid].ToString()))
                {
                    tg.Add(item);
                }
                else
                {
                    var pitem = idx[item[pid].ToString()] as Hashtable;
                    // 如果子节点不存在，建立子节点
                    if (!pitem.ContainsKey("children")) 
                    {
                        pitem["children"] = new List<Hashtable>();
                    }
                    // 插入到子节点中
                    var children = pitem["children"] as List<Hashtable>;
                    children.Add(item);
                }
            }

            // 4. 序列化哈希表，构造成easyui使用的格式
            string json = @"{""total"":" + tg.Count + @",""rows"":" + (new JavaScriptSerializer().Serialize(tg)) + @"}";

            return json;
        }

        public static string GetComboBoxJSON(   string idField,      
                                                string textField,
                                                System.Data.SqlClient.SqlDataReader reader)
        {
            var list = new List<Hashtable>();
            while (reader.Read())
            {
                var item = new Hashtable();
                for (var i = 0; i < reader.FieldCount; ++i)
                {
                    var name = reader.GetName(i);
                    if ((name == idField) || (name == textField) )
                    {
                        item[name] = reader[i];
                    }
                }
                list.Add(item);
            }
            return new JavaScriptSerializer().Serialize(list);
        }
    }
}
